package com.service;


import com.domain.Comment;
import com.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.Timer;
import java.util.concurrent.TimeUnit;

@Service
public class ApiCommentService {
    @Autowired
    private CommentRepository commentRepository;
    @Autowired
    private RedisTemplate redisTemplate;
    public Comment findById(int comment_id){
        Object object = redisTemplate.opsForValue().get("comment_"+comment_id);
        if (object!=null){
            return (Comment) object;
        }else {
            Optional<Comment> optional = commentRepository.findById(comment_id);
            if (optional.isPresent()){
                Comment comment = optional.get();

                redisTemplate.opsForValue().set("comment_"+comment_id,comment, 1, TimeUnit.DAYS);

                return comment;
            }else {
                return null;
            }
        }
    }
    public Comment updateComment(Comment comment){
        commentRepository.updateComment(comment.getAuthor(), comment.getId());

        redisTemplate.opsForValue().set("comment_"+comment.getId(),comment);
        return comment;
    }
    public void deleteComment(int comment_id){
        commentRepository.deleteById(comment_id);
        redisTemplate.delete("comment_"+comment_id);
    }
}
